const { app, BrowserWindow } = require('electron')
const path = require('path')

//本地存储
const Store = require('electron-store');
const store = new Store();

//仅测试环境打开
store.set("resourcePath", '.') //测试环境
// store.set("resourcePath", process.resourcesPath) //正式环境

//file system 文件系统
const fs = require('fs')

//可执行程序：mac调用./wx window调用./wx.exe
var exeSuffix = ''
if (process.platform == 'darwin') {
  exeSuffix = '/wx'
}else{
  exeSuffix = "\\wx.exe"
}

function createWindow () {

  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      // preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true, //渲染进程允许调用NodeJS
      webSecurity: false,//禁用同源策略
    }
  })
  win.setAutoHideMenuBar(true)

  win.loadURL('http://localhost:8080/index.html')
  // win.loadURL('http://spider.17fpv.com')

  // win.loadFile('index.html')
  // win.webContents.openDevTools();
}

app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

//启动Express服务器
const api = require("./api")
api.APIServer(store.get("resourcePath"))


// In main process.
  const {ipcMain} = require('electron')
  ipcMain.on('asynchronous-message', (event, arg) => {
    console.log(arg) // prints "ping"
    event.sender.send('asynchronous-reply', 'pong')
  })

  ipcMain.on('start-python-crawl', (event, arg) => {
    // console.log(arg) // prints "ping"
    // event.returnValue = 'pong'

    const child_process = require('child_process')
    var workerProcess = child_process.exec(store.get("resourcePath") + exeSuffix + ' ' + arg.site + ' ' + store.get('baseDir') + ' ' + arg.html, function (error, stdout, stderr) {
      if (error) {
        console.log(error.stack)
        console.log('Error code: ' + error.code)
        console.log('Signal received: ' + error.signal)
      }
      console.log('stdout: ' + stdout)
      console.log('stderr: ' + stderr)
      console.log(store.get("resourcePath") + exeSuffix + arg.site + ' ' + store.get('baseDir') + ' ' + arg.html)
    })

    workerProcess.on('exit', function (code) {
      console.log('子进程已退出，退出码 ' + code)
      // 异步回复
      event.reply('start-python-crawl-reply', 'ok')
    })


  })
